package com.controller;

import com.alibaba.fastjson.JSON;
import com.bean.JwtOperation;
import com.config.RsaProperties;
import com.constant.AppConstant;
import com.dto.JsonResult;
import com.dto.User;
import com.entity.UserInfo;
import com.exception.DisabledLoginException;
import com.service.UserService;
import com.utils.RsaUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


/**
 * @author Yadasu
 * @date 2020/12/21 9:34
 */
@RestController
public class LoginAndLogOutController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JwtOperation jwtOperation;


    /**
     * 用户登录
     * @param userInfo
     * @return
     */
    @PostMapping("/api/user/login")
    public JsonResult login(@RequestBody UserInfo userInfo)  {
        // 密码解密
        try{
            String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, userInfo.getPassword());
            return userService.login(userInfo.getUsername(), password);
        }catch (Exception e){
            throw new DisabledLoginException("用户名或密码错误");
        }

    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/api/user/getInfo")
    public JsonResult checkLogin() {

        if (stringRedisTemplate.hasKey(AppConstant.DEFAULT_NAME_PREFIX) != null) {
            String token = stringRedisTemplate.opsForValue().get(AppConstant.DEFAULT_NAME_PREFIX);
            Claims userClaims = jwtOperation.parseJwt(token);
            User user = JSON.parseObject(String.valueOf(userClaims.get("user")), User.class);
            return JsonResult.buildSuccess(200, user);
        } else {
            throw new DisabledLoginException("token不存在或已过期");
        }

    }


    /**
     * 登出
     * @return
     */
    @PostMapping("/api/user/logout")
    public JsonResult logout() {
        stringRedisTemplate.delete(AppConstant.DEFAULT_NAME_PREFIX);
        return JsonResult.buildSuccess(200, "成功登出");
    }

}
